import cv2
import os

def crop_center(image_path, output_path, crop_size=640):
    # 读取图片
    img = cv2.imread(image_path)
    if img is None:
        print(f"无法读取图片: {image_path}")
        return

    # 获取图片尺寸
    h, w, _ = img.shape

    # 计算中心点
    center_x, center_y = w // 2, h // 2

    # 计算裁剪区域的左上角坐标
    x1 = max(center_x - crop_size // 2, 0)
    y1 = max(center_y - crop_size // 2, 0)

    # 计算裁剪区域的右下角坐标
    x2 = min(center_x + crop_size // 2, w)
    y2 = min(center_y + crop_size // 2, h)

    # 裁剪图片
    cropped_img = img[y1:y2, x1:x2]

    # 确保裁剪出的图片尺寸符合 640x640
    if cropped_img.shape[0] != crop_size or cropped_img.shape[1] != crop_size:
        cropped_img = cv2.resize(cropped_img, (crop_size, crop_size))

    # 保存裁剪后的图片
    cv2.imwrite(output_path, cropped_img)
    print(f"裁剪完成，保存至: {output_path}")

# 示例调用
input_image = "trmplate.jpg"  # 输入图片路径
output_image = "template_640.jpg"  # 裁剪后图片保存路径
crop_center(input_image, output_image)
